
import { Space, Button, Form, Select, Input, Table, Tag, Modal } from "antd";
import { useEffect, useState } from "react";
import userApi from "../../api/userApi";
const { confirm } = Modal;

export default function userList() {

  const [isLoading, setIsLoading] = useState(false);

  const [searchForm] = Form.useForm();

  const [filterParams, setFilterParams] = useState({ pageNum: 1, pageSize: 3, })

  const [users, setUsers] = useState([])

  const [total, setTotal] = useState(0);

  const [delIds, setDelIds] = useState([]);

  const [editForm] = Form.useForm();


  const searchData = (searchForm) => {
    setFilterParams({ ...filterParams, ...searchForm })
  }

  const reset = () => {
    searchForm.resetFields();
    setFilterParams({ pageNum: 1, pageSize: 3 })
  }

  useEffect(() => { getUserList() }, [filterParams])

  const [isModalOpen, setIsModalOpen] = useState(false);

  const getUserList = async () => {
    setIsLoading(true);
    const { records, total } = await userApi.getUserList(filterParams)
    records.forEach(user => {
      user.key = user.userId
    });
    setUsers(records)
    setTotal(total)
    setIsLoading(false);
  }

  const delUsers = (id) => {
    console.log('id:', id);
    confirm({
      title: "确定要删除吗？",
      async onOk() {
        const ids = id ? [id] : delIds;
        await userApi.deleteUsers(ids)
        setFilterParams({ ...filterParams, pageNum: 1 })
        setDelIds([])
      }
    })
  }

  const columns = [
    {
      title: "用户编号",
      dataIndex: 'userId',
      align: 'center',
      key: 'userId',
    },
    {
      title: "用户名",
      dataIndex: 'userName',
      align: 'center',
      key: 'userName',
    },
    {
      title: "操作",
      dataIndex: 'userId',
      align: 'center',
      key: 'userId',
      render: (text, record) => (
        <div>
          <Button onClick={() => openEdit(record)}>编辑</Button>
          <Button onClick={() => delUsers(record.userId)}>删除</Button>
        </div>
      )
    },
  ]

  const [editId, setEditId] = useState();


  const openEdit = async (record) => {
    const data = await userApi.getByKey(record)
    setIsModalOpen(true);
    setEditId(record.userId)
    editForm.setFieldsValue(data);

  };



  const onSelectChange = (rowKeys) => {
    setDelIds(rowKeys);
  };

  const handleOk = async () => {
    const data = editForm.getFieldsValue();
    await userApi.addUser(data);
    setFilterParams({ ...filterParams, pageNum: 1 })
    editForm.resetFields();
    setIsModalOpen(false)
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    editForm.resetFields();
  };

  const paginationChange = (pageNum, pageSize) => {
    setFilterParams({
      ...filterParams,
      pageNum
    })
  }

  return (
    <div>
      <Space>
        <Space>
          <Button onClick={getUserList}>刷新</Button>
          <Button type="primary" onClick={() => setIsModalOpen(true)}>新增</Button>
          <Button danger onClick={() => delUsers()} disabled={!delIds.length}>删除</Button>
        </Space>
        <Form layout="inline" form={searchForm} onFinish={searchData}>
          <Form.Item name="userName">
            <Input placeholder="请输入用户名搜索">
            </Input>
          </Form.Item>
          <Space>
            <Button type="primary" htmlType="submit">搜索</Button>
            <Button onClick={() => reset()}>重置</Button>
          </Space>
        </Form>

      </Space>
      <Table
        bordered
        loading={isLoading}
        dataSource={users}
        columns={columns}
        rowSelection={{
          type: "checkbox",
          onChange: onSelectChange,
        }}
        pagination={{
          current: filterParams.pageNum,
          pageSize: filterParams.pageSize,
          showQuickJumper: true,
          total: total,
          onChange: paginationChange
        }}
      />
      <Modal title={editId ? "编辑" : "新增"} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} >
        <Form form={editForm} >
          <Form.Item label="用户id" name="userId" hidden>
            <Input />
          </Form.Item>
          <Form.Item label="用户名" name="userName">
            <Input />
          </Form.Item>
          <Form.Item label="密码" name="passWord">
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}